<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-05-26
 * Time: 21:35
 */

namespace app\common\model;


use app\common\exception\BusinessException;
use app\common\exception\ParameterException;
use app\common\validate\IDMustBeRequire;
use think\model\concern\SoftDelete;
use app\admin\validate\Business as Validate;
use app\common\model\BusinessTitle as BusinessTitleModel;

class Business extends BaseModel
{
    protected $hidden = ['create_time','update_time','delete_time'];

    // 使用软删除
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    public function businessTitle()
    {
        return $this->hasMany('BusinessTitle','business_id','id');
    }

    public function businessAdvisoryUser()
    {
        return $this->hasMany('BusinessAdvisoryUser','business_id','id');
    }

    /**
     * 获取业务的分页数据
     * @param array $params
     * @return \think\Paginator
     */
    public static function getPaginationList(array $params)
    {
        static::validatePaginationData($params);

        $static = new static();

        foreach ($params as $name => $value) {
            $value = trim($value);
            switch ($name) {
                case 'title':
                    if (!empty($value)) {
                        $like_text = '%' . $value . '%';
                        $static = $static->whereLike('title', $like_text);
                    }
                    break;
                case 'sort_order':
                    if (!empty($value)) {
                        $static = $static->order($params['sort_prop'], $value == 'descending' ? 'desc' : 'asc');
                    }
                    break;
            }
        }

        return $static
            ->paginate([
                'page' => $params['page'],
                'list_rows' => $params['limit']
            ], false);
    }

    /**
     * 根据id获取业务信息
     * @param $id
     * @return array|\think\Model|null
     */
    public static function getBusinessByID($id)
    {
        $validate = new IDMustBeRequire();
        if (!$validate->check(['id'=>$id])) {
            throw new ParameterException([
                'msg' => $validate->getError(),
            ]);
        }

        $static = new static;
        $result = $static->with(['businessTitle','businessTitle.businessData'])
            ->find($id);

        if (!$result) {
            throw new BusinessException();
        } else {
            // 对读取到数据进行兼容性处理
            $data = $result->hidden(['businessTitle'=>['businessData.title_id']])->toArray();
            foreach ($data['businessTitle'] as $key => $value) {
                $data['business_data'][$key] = [
                    'title' => $value['title'],
                    'data' => $value['businessData']
                ];
            }
            unset($data['businessTitle']);
            return $data;
        }
    }

    /**
     * 获取指定数量的业务标题
     * @param $limit
     * @return array
     */
    public static function getBusinessTitle($limit)
    {
        $data = static::where('status','=',1)
            ->field(['id','title'])
            ->limit($limit)
            ->order(['sort'=>'ASC'])
            ->select();

        if ($data->isEmpty()) {
            throw new BusinessException([
                'msg' => '业务标题数据不存在',
                'errorCode' => 40011,
            ]);
        }

        return $data->toArray();
    }

    /**
     * 获取对应操作类型的用户分页数据
     * @param $params
     * @return \think\Paginator
     */
    public static function getOperationUserPaginationList(array $params)
    {
        static::validatePaginationData($params);

        $static = static::find($params['id']);

        switch ($params['type']) {
            case 'advisory' :
                $static = $static->businessAdvisoryUser()->with('user');
                break;
        }

        return $static->paginate([
            'page' => $params['page'],
            'list_rows' => $params['limit'],
        ],false);
    }

    /**
     * 添加业务信息
     * @param array $data
     * @return bool
     */
    public static function addBusiness(array $data)
    {

        $validate = new Validate();
        if (!$validate->scene('add')->check($data)) {
            throw new ParameterException([
                'msg' => $validate->getError(),
            ]);
        }

        self::handleSubmitBusinessData($data);

        $static = new static();

        $static->startTrans();

        try {
            // 首先将基础输入写入数据库，获取到对应的id
            $static->allowField(['title','query_count','sort','status'])
                ->save($data);
            $static = $static->refresh();

            // 然后依次插入业务流程标题和内容
            foreach ($data['business_data'] as $key => $value) {
                $businessTitle = new BusinessTitleModel();
                $businessTitle->allowField(['title','business_id'])
                    ->save([
                        'title' => $value['title'],
                        'business_id' => $static->id,
                    ]);
                $businessTitle = $businessTitle->refresh();
                $businessTitle->businessData()->saveAll($value['data']);
            }

            $static->commit();
        }catch (\Exception $e) {
            $static->rollback();
            return false;
        }

        return true;
    }

    /**
     * 编辑业务信息
     * @param array $data
     * @return bool
     */
    public static function editBusiness(array $data)
    {
        $validate = new Validate();
        if (!$validate->scene('edit')->check($data)) {
            throw new ParameterException([
                'msg' => $validate->getError(),
            ]);
        }

        self::handleSubmitBusinessData($data);

        $static = static::find($data['id']);

        $static->startTrans();

        try {
            // 首先将基础输入写入数据库，获取到对应的id
            $static->allowField(['id','title','query_count','sort','status'])
                ->save($data);
            $static = $static->refresh();

            // 首先删除旧的业务标题和数据的数据
            $businessTitleID = BusinessTitleModel::where('business_id','=',$static->id)
                ->column('id');
            foreach ($businessTitleID as $item) {
                $businessTitleDelete = BusinessTitleModel::with(['businessData'])
                    ->find($item);
//                $test1 = $businessTitleDelete->getRelation();
                // 记得要设置对应关联表的主键或者修改主键对应的字段值
                $businessTitleDelete->together(['businessData'])->delete();
            }

            // 然后依次插入业务流程标题和内容
            foreach ($data['business_data'] as $key => $value) {
                $businessTitle = new BusinessTitleModel();
                $businessTitle->allowField(['title','business_id'])
                    ->save([
                        'title' => $value['title'],
                        'business_id' => $static->id,
                    ]);
                $businessTitle = $businessTitle->refresh();
                $businessTitle->businessData()->saveAll($value['data']);
            }

            $static->commit();
        }catch (\Exception $e) {
            $static->rollback();
            return false;
        }

        return true;
    }

    /**
     * 判断用户是否已经存在查询列表用户列表中
     * @param $id
     * @return bool
     */
    public static function checkAdvisoryUser($id)
    {
        // 获取当前用户的uid
        $uid = MpApiUserToken::getCurrentUID();

        // 进行模型关联查询，查看是否查询到该id的用户
        $business = static::find($id);
        $advisoryUser = $business->businessAdvisoryUser()
            ->where('user_id','=',$uid)
            ->find();

        // 判断是否为空
        if (!empty($advisoryUser)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 添加咨询用户关系数据
     * @param $id
     * @return mixed
     */
    public static function addAdvisoryUser($id)
    {
        $validate = new IDMustBeRequire();
        if (!$validate->check(['id' => $id])) {
            throw new ParameterException([
                'msg' => $validate->getError()
            ]);
        }

        // 获取当前用户的uid
        $uid = MpApiUserToken::getCurrentUID();

        // 将当前用户的uid存到数据库中
        $static = static::find($id);
        $static->query_count++;
        $static->save();
        // 添加用户到关系表中
        $static->businessAdvisoryUser()->save([
            'user_id'=>$uid
        ]);

        return $static->query_count;
    }

    /**
     * 处理前端传过来的数据
     * @param $data
     */
    private static function handleSubmitBusinessData(&$data)
    {
//        foreach ($data['business_data'] as $key => &$value) {
//            if (empty($value['title']) || $value['title'] === '请填写子项标题') {
//                array_splice($data['business_data'], $key, 1);
//                continue;
//            }
//            foreach ($value['data'] as $data_key => $data_value) {
//                if (empty($data_value['title']) || empty($data_value['sub_title'])) {
//                    array_splice($value['data'], $data_key, 1);
//                    continue;
//                }
//            }
//        }

        foreach ($data['business_data'] as $key => &$value) {
            if (empty($value['title']) || $value['title'] === '请填写子项标题') {
                unset($data['business_data'][$key]);
                continue;
            }
            foreach ($value['data'] as $data_key => $data_value) {
                if (empty($data_value['title']) || empty($data_value['sub_title'])) {
                    unset($value['data'][$data_key]);
                    continue;
                }
            }
            $value['data'] = array_values($value['data']);
        }
        $data['business_data'] = array_values($data['business_data']);


    }
}